﻿using AntdUI;
using CKS.AGV.Core.Enum;
using CKS.AGV.Server.ViewModel;
using CKS.Core.Framework;
using CKS.Core.Framework.Models;
using CKS.Models;
using Flurl;
using Flurl.Http;
using FreeSql;
using Mapster;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CKS.AGV.Server.Controls
{
    public partial class TasksTable : UserControl
    {
        IFreeSql<MesDB> fsql;
        IBaseRepository<agv_convey_tasks> repoTasks;
        public TasksTable()
        {
            InitializeComponent();
           
            this.Load += TasksTable_Load;
        }

        private void TasksTable_Load(object sender, EventArgs e)
        {
            try
            {
                InitTable();
                if (DesignMode)
                    return;
                fsql = AppCache.GetServiceProvider().GetService<IFreeSql<MesDB>>();
                repoTasks = fsql.GetRepository<agv_convey_tasks>();
                Run();
            }
            catch (Exception)
            {

            }

        }

        private void InitTable()
        {
            table1.EditMode = TEditMode.None;
            table1.Columns = new ColumnCollection();

            table1.Columns.Add(new Column("Id", "任务编号") { Fixed = true, KeyTree = "SubItems", Align = ColumnAlign.Center, Width = "100" });
            table1.Columns.Add(new Column("Desc", "任务描述") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });
           // table1.Columns.Add(new Column("TaskType", "任务类型") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });
           // table1.Columns.Add(new Column("PartType", "零件类型") { Fixed = true, Style = new Table.CellStyleInfo() { BackColor = Color.Yellow, ForeColor = Color.Black } });
            table1.Columns.Add(new Column("MatchOut", "出料匹配") { Fixed = true, Style = new Table.CellStyleInfo() {  } });
            //table1.Columns.Add(new Column("EndPathPoint", "终点") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            
            table1.Columns.Add(new Column("IsTest", "是否测试") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("TaskStatus", "任务状态") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("HikTaskCode", "Hik任务编号") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("SendHex", "路径") { Fixed = true, Style = new Table.CellStyleInfo() { } });

            table1.Columns.Add(new Column("LastAgvReqStatus", "AGV最后状态") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("LastAgvRspStatus", "Server最后状态") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("CreatedTime", "创建时间") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            table1.Columns.Add(new Column("EndTime", "完成时间") { Fixed = true, Style = new Table.CellStyleInfo() { } });
            
            if(ShowCurrentTask)//只有当前任务才需要
                table1.Columns.Add(new Column("Operate", "操作") { Fixed = true });
           
            table1.Bordered = true;
            table1.EnableHeaderResizing = true;
            table1.EmptyHeader = true;
            table1.Gap = 6;
            table1.VisibleHeader = true;
            table1.ClipboardCopy = false;
            table1.Binding(DataSource);

            table1.CellButtonClick += Table1_CellButtonClick;
        }

        private  void Table1_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            var item = e.Record as View_convey_tasks;
            switch (e.Btn.Id)
            {
                case "cancel":
                  
                    var task = item.Adapt<agv_convey_tasks>();
                    repoTasks.Attach(task);
                    task.CancelState = 1;
                    repoTasks.Update(task);
                    MessageBoxShow("已提交取消");


                    break;
            }
        }

        [Description("true显示当前任务false显示已完成任务"), Category("数据")]
        public bool ShowCurrentTask {  get; set; } = true;


        AntList<View_convey_tasks> DataSource = new AntList<View_convey_tasks>();
        public void QueryTask()
        {

           var ls  =  repoTasks.WhereIf(ShowCurrentTask, a => (int)a.TaskStatus < 10)
                      .WhereIf(!ShowCurrentTask, a => (int)a.TaskStatus >= 10)
                      .OrderByIf(ShowCurrentTask,a=>a.Id)
                      .OrderByDescending(!ShowCurrentTask,a=>a.EndTime)
                      .Take(100)
                      .ToList().Adapt<List<View_convey_tasks>>();

            var  Removes = DataSource.Where(a => ls.Find(b => b.Id == a.Id) == null);
            foreach (var s in Removes)
            {
                DataSource.Remove(s);
            }


            ls.Reverse();
            foreach (var item in ls)
            {
                var one =DataSource.ToList().Find(a => a.Id == item.Id);
                if (one != null)
                {
                    
                    item.MapTo(one);
                }
                else
                    DataSource.Insert(0,item);
            }
        }


        public void Run() // 每秒刷新一次任务列表
        {
            
            Task.Factory.StartNew(async () => {

                while (this.IsHandleCreated)
                {
                    try
                    {
                        QueryTask();
                        await Task.Delay(1000);

                    }
                    catch (Exception)
                    {


                    }

                }
                
            
            
            });
        }

        public void MessageBoxShow(string message, TType type = TType.Info)
        {
            try
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this.FindForm(), "消息", message)
                {
                    Icon = type,
                    //内边距
                    Padding = new Size(24, 20),
                    OkText = "确认",
                    CancelText = null,
                });
            }
            catch (Exception)
            {

            }
        }

    }
}
